<template>
  <div>
    <el-select
      :value="row.status || row.memberStatus"
      @change="toStatus => changeStatus(toStatus, row)"
    >
      <el-option
        v-if="isShowWhite && row.status !== NORMAL"
        :value="WHITE"
        :label="$t('white_list')"
      ></el-option>
      <el-option
        v-for="(item, key) in noWhiteOption"
        :key="key"
        :value="key"
        :label="noWhiteOption[key]"
      />
    </el-select>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="$t('adjust_membership_status')"
      width="1000px"
    >
      <el-form label-width="150px" class="t-l-l">
        <el-form-item
          :label="$t('white_list_protection') + ':'"
          v-if="isShowWhite && whileRuleList.length > 0"
        >
          <el-table :data="whileRuleList" border>
            <el-table-column
              :label="$t('serial_number')"
              width="60"
              align="center"
            >
              <template slot-scope="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column prop="ruleName" :label="$t('protection_rules')" />
            <el-table-column :label="$t('protection_time')" width="140">
              <template slot-scope="scope">
                <el-select v-model="scope.row.days" size="small">
                  <template v-for="(item, key) in cycleDic">
                    <el-option
                      v-if="Number(key.split('_')[1]) >= scope.row.limitDays"
                      :label="item"
                      :key="key"
                      :value="key.split('_')[1]"
                    />
                  </template>
                  <el-option
                    v-if="isRoot"
                    :value="3650"
                    :label="$t('permanent')"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item :label="$t('status_change') + ':'">
          <span>
            {{ statusMap[form.fromStatus] }} > {{ statusMap[form.toStatus] }}
          </span>
        </el-form-item>

        <el-form-item :label="$t('change_type') + ':'">
          <div v-if="form.toStatus == NORMAL || form.toStatus == WHITE">
            <el-select class="w-400" v-model="form.reasonType">
              <el-option
                v-for="(item, key) in normalTypeOption"
                :key="key"
                :value="key"
                :label="normalTypeOption[key]"
              />
            </el-select>
          </div>
          <div v-else>
            <el-select class="w-400" v-model="form.reasonType">
              <el-option
                v-for="(item, key) in noNormalTypeOption"
                :key="key"
                :value="key"
                :label="noNormalTypeOption[key]"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item :label="$t('change_reason') + ':'">
          <el-input
            v-model="form.reason"
            :placeholder="$t('words_5_1000')"
            :rows="5"
            type="textarea"
            :maxlength="maxlength"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
        <el-button
          type="primary"
          :disabled="btnLoading"
          :loading="btnLoading"
          @click="submit"
          >{{ $t('confirm') }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addWhiteApi,
  isWhiteRules,
  existApplyApi,
  changeStatusApi
} from '@/api/user-exception-filtering/abnormal-behavior';

const WHITE = 'WHITE';
const NORMAL = 'NORMAL';
const maxlength = 1000;

export default {
  props: {
    row: {
      type: Object,
      default: () => {}
    },

    pageName: {
      type: String,
      default: ''
    },

    // 除了会员查询页面 其他页面不显示白名单选项
    isShowWhite: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      WHITE,
      NORMAL,
      maxlength,
      isRoot: Boolean(localStorage.getItem('full_rule_name')), // 是否是拥有永久权限用户
      dialogVisible: false,
      btnLoading: false,
      whileRuleList: [],

      form: {
        memberId: null,
        fromStatus: null,
        toStatus: null,
        ruleGroupNameList: null,
        reasonType: null,
        reason: null
      },

      noWhiteOption: {
        GREY: this.$t('grey_list'),
        BLACK: this.$t('black_list'),
        NOTSURE: this.$t('suspicious_situation'),
        NORMAL: this.$t('normal')
      },

      statusMap: {
        GREY: this.$t('grey_list'),
        BLACK: this.$t('black_list'),
        NOTSURE: this.$t('suspicious_situation'),
        NORMAL: this.$t('normal'),
        WHITE: this.$t('normal') // 这里白名单也显示为正常
      },

      normalTypeOption: {
        1: this.$t('recovery_system_abnormal'),
        2: this.$t('recovery_human_being_error'),
        3: this.$t('recovery_other_causes')
      },

      noNormalTypeOption: {
        4: this.$t('abnormal_fraud_accounts'),
        5: this.$t('abnormal_too_many_accounts'),
        6: this.$t('abnormal_abnormal_suspection'),
        7: this.$t('abnormalcomment_improperly'),
        9: this.$t('abnormal_using_plug_in_multiple'),
        10: this.$t('exception__too_many_ads'),
        11: this.$t('exception__publishing_content_infringement'),
        12: this.$t('exception_abnormal_publishing_frequency'),
        8: this.$t('abnormal_other_causes')
      },

      cycleDic: {
        day_1: this.$t('a_1_day'),
        day_3: this.$t('a_3_days'),
        day_7: this.$t('a_7_days')
      }
    };
  },

  methods: {
    async changeStatus(toStatus, row) {
      const memberId = row.id || row.memberId;
      const fromStatus = row.memberStatus || row.status;
      const { ruleGroupNameList } = row;

      try {
        // 判断是否有申请未处理
        const isApplying = await this.judgeIsApplying(memberId);

        if (isApplying) {
          this.$message.warning(
            this.$t(
              'unable_to_change_please_process_the_exception_cancellation_application_of_this_user_first'
            )
          );
          return;
        }
        this.form = {
          ...this.form,
          toStatus,
          ruleGroupNameList,
          fromStatus,
          memberId,
          reasonType: null,
          reason: null
        };
        this.dialogVisible = true;

        // 变更为白名单
        if (toStatus == WHITE) {
          this.turnToWhite();
        }
      } catch (e) {
        throw e;
      }
    },

    submit() {
      const { reasonType, reason, memberId, fromStatus, toStatus } = this.form;
      const { pageName: page, whileRuleList } = this;

      const ruleGroupNameList = [
        {
          days: '',
          frequency: '',
          operator: '',
          periodOfTime: '',
          ruleName: `人工判断：${reason}`,
          ruleType: 3,
          value: ''
        }
      ];

      if (!reasonType) {
        this.$message.warning(this.$t('please_select_change_type'));
        return;
      }

      if (!reason || reason.trim() == '' || reason.length < 5) {
        this.$message.warning(
          this.$t('the_word_number_range_of_reason_for_change_is_5_1000')
        );
        return;
      }

      const arr = [
        {
          memberId,
          fromStatus,
          toStatus,
          reasonType: Number(reasonType),
          reason,
          ruleGroupNameList
        }
      ];

      if (toStatus == 'WHITE') {
        this.changeAsWhite(
          {
            page,
            whiteList: [
              {
                memberId,
                fromStatus,
                toStatus,
                reasonType: Number(reasonType),
                reason,
                ruleGroupNameList: whileRuleList
              }
            ]
          },
          memberId
        );
      } else {
        this.changeAsNotWhite(
          {
            page,
            changeStatusArr: arr
          },
          memberId
        );
      }
    },

    async changeAsNotWhite(query, memberId) {
      this.btnLoading = true;
      try {
        const { code, msg } = await changeStatusApi(query);
        this.btnLoading = false;
        if (code == 200) {
          const message = this.$t(
            'member_xxx_status_modified_successfully'
          ).replace('XXX', memberId);
          this.$message.success(message);
          this.dialogVisible = false;
          this.$emit('changeStatusSuccee');
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.btnLoading = false;
        throw e;
      }
    },

    async changeAsWhite(query, memberId) {
      this.btnLoading = true;
      try {
        const { code, msg } = await addWhiteApi(query);
        this.btnLoading = false;
        if (code == 200) {
          const message = this.$t(
            'member_xxx_status_modified_successfully'
          ).replace('XXX', memberId);
          this.$message.success(message);
          this.dialogVisible = false;
          this.$emit('changeStatusSuccee');
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.btnLoading = false;
        throw e;
      }
    },

    async judgeIsApplying(memberId) {
      let flag = false;
      try {
        const { code, data } = await existApplyApi({ memberId });
        // 0 没有申请待处理 1 有申请待处理
        if (code == 200 && data == 1) {
          flag = true;
        } else {
          flag = false;
        }
      } catch (e) {
        flag = false;
      }

      return flag;
    },

    async turnToWhite() {
      const { id, ruleGroupNameList } = this.row;

      // 人工判白名单则没有保护时长
      const ruleList = ruleGroupNameList.filter(item => item.ruleType != 3);

      try {
        const { code, data } = await isWhiteRules({
          member_id: id,
          ruleGroupNameList: ruleList
        });

        if (code == 200) {
          if (data.length == 0) return;

          const obj = {};
          const whileRuleList = [];

          data.forEach(item => {
            const rule = `${item.days};;${item.frequency};;${item.operator};;${
              item.periodOfTime
            };;${item.ruleType};;${item.value}`;
            const { ruleName } = item;

            if (!Object.keys(obj).includes(ruleName)) {
              obj[ruleName] = rule;
            } else if (Object.keys(obj).length != 0 && obj[ruleName]) {
              // 过滤重复规则，取周期最大值
              obj[ruleName] =
                obj[ruleName].split(';;')[0] > item.days ? obj[ruleName] : rule;
            }
          });

          Object.keys(obj).forEach(item => {
            const info = obj[item].split(';;');
            whileRuleList.push({
              ruleName: item,
              days: info[0],
              limitDays: info[0],
              frequency: info[1],
              operator: info[2],
              periodOfTime: info[3],
              ruleType: info[4],
              value: info[5]
            });
          });

          this.whileRuleList = whileRuleList;
          console.log(this.whileRuleList)
        }
      } catch (e) {
        throw e;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.t-l-l {
  text-align: left;
}
</style>
